var express = require('express');
var mongoose = require('mongoose');

var router = express.Router();

var Quiz = mongoose.model('Quiz');
var Question = mongoose.model('Question');
var Answer = mongoose.model('Answer');

//pobranie wszystkich dostępnych quizów
router.get('/', function(req, res, next) {
  Quiz.find(function(err, quizes) {
    if(err) { res.send(err.message); return; }
    res.json(quizes);
  });
});

//definicja i pobranie danych z bazy o quizie o zadanym id
router.param('id', function(req, res, next, id) {
  var query = Quiz.findById(id);

  query.exec(function(err, quiz) {
    if(err) { return next(err); }
    if(!quiz) { return next(new Error('Nie znaleziono quizu!')); }

    req.quiz = quiz;
    return next();
  });
});

//pobieranie szczegółów o quizie wraz z pytaniami
router.get('/:id', function(req, res, next) {
  Quiz.findById(req.quiz._id).populate('questions').exec(function(err, quiz) {
    Answer.populate(quiz.questions, {path: 'answers'}, function(err, questions) {
      questions.forEach(function(question) {
        console.log('Question: %s', question.content);
        question.answers.forEach(function(answer) {
          console.log('Possible answer: %s', answer.content);
        });
      })
      res.json(quiz);
    });
  });
});

//usuwanie quizu
router.delete('/:id', function(req, res) {
  Quiz.remove({
    _id: req.params.quiz
  }, function(err, quiz) {
      if (err) { return res.send(err); }
      res.json({ message: 'Sukces: usuniecie quizu'});
    });
});

//dodawanie nowego quizu
router.post('/new', function(req, res, next) {
  var quiz = new Quiz(req.body);

  quiz.save(function(err, quiz) {
    if(err) { return next(err); }
    res.json(quiz);
  })
});

module.exports = router;